import dayjs from "dayjs";
import { usePublicHooks } from "@/views/system/hooks";
import { message } from "@/utils/message";
import { addDialog } from "@/components/ReDialog";
import editForm from "../form.vue";
import { reactive, ref, onMounted, h, toRaw } from "vue";
import { type FormItemProps } from "./types";
import { type PaginationProps } from "@pureadmin/table";
import { ElMessageBox } from "element-plus";

import {
  getAICodList,
  //getAICodByID,
  saveAICode,
  delAICode
} from "@/api/systemcofig";
export function weichatMessgaeConfig() {
  const dataList = ref([]);
  const loading = ref(false);
  const formRef = ref();
  const switchLoadMap = ref({});

  const pagination = reactive<PaginationProps>({
    total: 0,
    pageSize: 10,
    currentPage: 1,
    background: true
  });
  const { switchStyle } = usePublicHooks();
  const columns: TableColumnList = [
    {
      label: "编号",
      prop: "id",
      minWidth: 100,
      sortable: "custom"
    },
    {
      label: "AI名称",
      prop: "aiName",
      minWidth: 120,
      sortable: "custom"
    },
    {
      label: "AI头像",
      slot: "image",
      minWidth: 150
    },
    {
      label: "是否有效",
      minWidth: 130,
      cellRenderer: scope => (
        <el-switch
          size={scope.props.size === "small" ? "small" : "default"}
          loading={switchLoadMap.value[scope.index]?.loading}
          v-model={scope.row.isFalg}
          active-value={1}
          inactive-value={0}
          active-text="已启用"
          inactive-text="已停用"
          inline-prompt
          style={switchStyle.value}
          onChange={() => onChange(scope as any)}
        />
      )
    },

    {
      label: "创建时间",
      minWidth: 180,
      prop: "addTime",
      formatter: ({ addTime }) => dayjs(addTime).format("YYYY-MM-DD HH:mm:ss")
    },
    {
      label: "操作",
      fixed: "right",
      width: 240,
      slot: "operation"
    }
  ];

  function handleSizeChange(val: number) {
    pagination.pageSize = val;
    onSearch();
  }

  function handleCurrentChange(val: number) {
    pagination.currentPage = val;
    onSearch();
  }

  // async function onSearch() {
  //   loading.value = true;
  //   const Result = await getSysWeiXinMsgModeAllList(toRaw(pagination));
  //   dataList.value = Result.result;
  //   pagination.total = Result.onePage.total;
  //   pagination.pageSize = Result.onePage.pageSize;
  //   pagination.currentPage = Result.onePage.currentPage;
  //   setTimeout(() => {
  //     loading.value = false;
  //   }, 500);
  // }
  function onChange({ row, index }) {
    ElMessageBox.confirm(
      `确认要<strong>${
        row.isFalg === 0 ? "停用" : "启用"
      }</strong><strong style='color:var(--el-color-primary)'>${
        row.aiName
      }</strong>吗?`,
      "系统提示",
      {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
        dangerouslyUseHTMLString: true,
        draggable: true
      }
    )
      .then(() => {
        switchLoadMap.value[index] = Object.assign(
          {},
          switchLoadMap.value[index],
          {
            loading: true
          }
        );
        setTimeout(async () => {
          switchLoadMap.value[index] = Object.assign(
            {},
            switchLoadMap.value[index],
            {
              loading: false
            }
          );
          //console.log(row);
          const Result = await saveAICode(row);
          if (Result.isSuccess) {
            message("已修改成功！", {
              type: "success"
            });
          } else {
            message(Result.msg, { type: "error" });
          }
        }, 300);
      })
      .catch(() => {
        row.isFalg === 0 ? (row.disate = 1) : (row.disate = 0);
      });
  }
  async function onSearch() {
    loading.value = true;
    const Result = await getAICodList(toRaw(pagination));
    dataList.value = Result.result;
    pagination.total = Result.pageInfo.total;
    pagination.pageSize = Result.pageInfo.pageSize;
    pagination.currentPage = Result.pageInfo.currentPage;

    setTimeout(() => {
      loading.value = false;
    }, 500);
  }

  async function handleDelete(row) {
    const Result = await delAICode({ id: row.id });
    if (Result.isSuccess) {
      message(`已删除名称为 ${row.tempName} 的数据`, {
        type: "success"
      });
      onSearch();
    } else {
      message(Result.msg, { type: "error" });
    }
  }

  onMounted(() => {
    onSearch();
  });

  function openDialog(title = "新增", row?: FormItemProps) {
    console.log("open", row);
    addDialog({
      title: `${title}AI配置`,
      props: {
        formInline: {
          id: row?.id ?? 0,
          aiName: row?.aiName ?? "",
          aiHead: row?.aiHead ?? "",
          aiSysMessage: row?.aiSysMessage ?? "",
          aiFirstUserMsg: row?.aiFirstUserMsg ?? "",
          apiKey: row?.apiKey ?? "",
          gmlURL: row?.gmlURL ?? "",
          cogVieURL: row?.cogVieURL ?? "",
          webMode: row?.webMode ?? "",
          knoMode: row?.knoMode ?? "",
          dataMode: row?.dataMode ?? "",
          drawMode: row?.drawMode ?? "",
          textModel: row?.textModel ?? "",
          isFalg: row?.isFalg ?? true,
          addUser: row?.addUser ?? "",
          addTime: row?.addTime ?? ""
        }
      },
      width: "40%",
      draggable: true,
      fullscreenIcon: true,
      closeOnClickModal: false,
      contentRenderer: () => h(editForm, { ref: formRef }),
      beforeSure: (done, { options }) => {
        const FormRef = formRef.value.getRef();
        const curData = options.props.formInline as FormItemProps;
        function chores() {
          message(`您${title}了名称为${curData.aiName}的这条数据`, {
            type: "success"
          });
          done();
          onSearch();
        }
        FormRef.validate(async valid => {
          if (valid) {
            console.log(curData);
            curData.addTime = "2024-5-6";
            curData.addUser = "0";
            const subResult = await saveAICode(curData);

            if (subResult.isSuccess) {
              chores();
            } else {
              message(subResult.msg, { type: "error" });
            }
          }
        });
      }
    });
  }

  const getConfigList = () => {
    console.log("this is a fnuntong");
  };

  return {
    getConfigList,
    columns,
    pagination,
    dataList,
    onSearch,
    loading,
    openDialog,
    handleDelete,
    handleSizeChange,
    handleCurrentChange
  };
}
